package com.shop.dao;

import com.mongodb.client.MongoCollection;
import com.mongodb.client.model.Filters;
import com.shop.bean.Product;
import com.shop.util.MongoDBUtil;
import org.bson.Document;
import org.bson.types.ObjectId;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

public class ProductDao {
    private MongoCollection<Document> collection;
    
    public ProductDao() {
        collection = MongoDBUtil.getDatabase().getCollection("products");
    }
    
    public void insert(Product product) {
        Document doc = new Document("name", product.getName())
                .append("price", product.getPrice())
                .append("stock", product.getStock())
                .append("description", product.getDescription())
                .append("customFields", product.getCustomFields());
        collection.insertOne(doc);
    }
    
    public void update(Product product) {
        Document doc = new Document("name", product.getName())
                .append("price", product.getPrice())
                .append("stock", product.getStock())
                .append("description", product.getDescription())
                .append("customFields", product.getCustomFields());
        collection.updateOne(Filters.eq("_id", product.getId()), new Document("$set", doc));
    }
    
    public void delete(String id) {
        if (!ObjectId.isValid(id)) {
            throw new IllegalArgumentException("Invalid ObjectId format");
        }
        collection.deleteOne(Filters.eq("_id", new ObjectId(id)));
    }
    
    public List<Product> findAll() {
        List<Product> products = new ArrayList<>();
        for (Document doc : collection.find()) {
            Product product = new Product();
            product.setId(doc.getObjectId("_id"));
            product.setName(doc.getString("name"));
            product.setPrice(doc.getDouble("price"));
            product.setStock(doc.getInteger("stock"));
            product.setDescription(doc.getString("description"));
            @SuppressWarnings("unchecked")
            Map<String, Object> customFields = (Map<String, Object>) doc.get("customFields");
            product.setCustomFields(customFields);
            products.add(product);
        }
        return products;
    }
} 